<?php
namespace app\extend\kline;

class Huobi
{
    protected static $http = 'https://api.huobi.pro';

    /**
     * 获取金额
     * @param $code
     * @return array|int[]
     */
    public static function getPrice($code)
    {
        $api = self::$http . "/market/detail/merged?symbol=".strtolower($code).'usdt';

        $result = curlGet($api);

        if(!isset($result['data']['tick'])){
            return [
                'price' => 0,
                'open' => 0,
                'close' => 0,
                'high' => 0,
                'low' => 0
            ];
        } else {
            return [
                'price' => $result['data']['tick']['amount'],
                'open' => $result['data']['tick']['open'],
                'close' => $result['data']['tick']['close'],
                'high' => $result['data']['tick']['high'],
                'low' => $result['data']['tick']['low'],
            ];
        }
    }

    /**
     * 获取
     * @param $code
     * @param $interval
     * @param $num
     * @return array|false
     */
    public static function getKline($code,$interval,$num)
    {
        $timeArr = ['1'=>'1min', '5'=>'5min', '30'=>'30min', '60'=>'1hour', 'd'=>'1day'];

        $api = self::$http."/market/history/kline?period=".$timeArr[$interval]."&size=".$num."&symbol=".strtolower($code).'usdt';

        $result = curlGet($api);

        $data = self::_getFormatLine($result['data']['data']);

        return $data;
    }

    /**
     * 获取格式化K线数据
     * @param $data
     * @return array|false
     */
    private static function _getFormatLine($data) {

        $result = [];

        if (empty($data)){
            return false;
        }

        foreach ($data as $val) {
            $time = $val['id'] * 1000;
            $result[$time] = [
                'timestamp' => $time,
                'open' => $val['open'],
                'close' => $val['close'],
                'high' => $val['high'],
                'low' => $val['low'],
                'volume' => $val['vol']
            ];
        }

        ksort($result);
        return array_values($result);
    }
}